import __config from "../../../config/env";

const app = getApp()
const chooseLocation = requirePlugin('chooseLocation');

Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    theme: app.globalData.theme, //全局颜色变量
    orderConfirmData: [],
    salesPrice: 0,
    paymentPrice: 0,
    // 夜间服务费
    freightPrice: 0,
    userAddress: null,
    orderSubParm: {
      paymentType: '1',
      deliveryWay: '2'
    },
    loading: false,
    userInfo: null,
    pointsConfig: null,
    totalPointsDeduct: 0,
    totalPointsDeductPriceTemp: 0,
    totalPointsDeductPrice: 0,
    modalCoupon: '',
    spuIds: [],
    couponUserList: [],
    couponUser: null,
    totalCouponDeductPrice: 0,
    pointsCheckedValue: null,
    couponCheckedValue: null,
    freightMap: null, //各运费模块计数
    addressComponent: {
      city: null,
      address: null,
      longitude: null,
      latitude: null
    },
    userName: null,
    userPhone: null,
    picUrls: [],
    // 12月12日 12:00-13:59
    bookingTime: null,
    bookingStartTime: null,
    bookingEndTime: null
  },
  onShow() {
    let addressComponent = app.globalData.addressComponent || {}
    const location = chooseLocation.getLocation();
    if (location) {
      console.log("地址：" + location.address)
      addressComponent = {
        city: location.city,
        address: location.address,
        longitude: location.longitude,
        latitude: location.latitude,
        title: location.name
      }
    }
    if (addressComponent) {
      app.globalData.addressComponent = addressComponent
      this.setData({
        addressComponent: addressComponent
      });
    }
    // 更新希望上门时间
    if (app.globalData.bookingTime || !this.data.bookingStartTime) {
      this.setData({
        bookingTime: app.globalData.bookingTime
      })
      app.globalData.bookingTime = null
      this.loadFreightPrice()
    }
  },
  onLoad: function () {
    this.pointsConfigGet()
    this.userInfoGet()
    this.orderConfirmDo()
  },
  // 查询夜间服务费
  loadFreightPrice() {
    app.api.freightPriceGet({
      serviceCity: this.data.addressComponent.city,
      bookingTime: this.data.bookingTime || ''
    }).then(res => {
      let data = res.data
      this.setData({
        freightPrice: data.freightPrice,
        bookingStartTime: data.bookingStartTime,
        bookingEndTime: data.bookingEndTime
      })
    })
  },
  // 姓名
  bindUserNameInput: function (e) {
    this.setData({
      [`orderSubParm.userName`]: e.detail.value
    })
  },
  // 电话
  bindUserPhoneInput: function (e) {
    this.setData({
      [`orderSubParm.userPhone`]: e.detail.value
    })
  },
  // 问题描述
  userMessageInput(e) {
    this.setData({
      [`orderSubParm.userMessage`]: e.detail.value
    })
  },
  //获取订阅消息列表
  wxTemplateMsgList(id) {
    app.api.wxTemplateMsgList({
        enable: '1',
        // 用途，2：订单支付成功；3、接单提醒；4、结单提醒
        useTypeList: ['3', '4']
      }).then(res => {
        let tmplIds = []
        res.data.forEach(item => {
          tmplIds.push(item.priTmplId)
        })
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            console.log(res)
          },
          complete() {
            wx.redirectTo({
              url: '/pages/order/order-detail/index?callPay=true&id=' + id
            })
          }
        })
      })
  },
  deliveryWayChange(e) {
    this.setData({
      [`orderSubParm.deliveryWay`]: e.detail.value,
      freightMap: null
    })
    this.orderConfirmDo()
  },
  orderConfirmDo() {
    // 本地获取参数信息
    let that = this
    wx.getStorage({
      key: 'param-orderConfirm',
      success: function (res) {
        let orderConfirmData = res.data
        let salesPrice = 0 //订单金额
        let totalPointsDeduct = 0 //最多可用积分数
        let totalPointsDeductPriceTemp = 0 //最多可用积分数抵扣金额
        let spuIds = null
        orderConfirmData.forEach((orderConfirm, index) => {
          if (spuIds) {
            spuIds = spuIds + ',' + orderConfirm.spuId
          } else {
            spuIds = orderConfirm.spuId
          }
          salesPrice = (Number(salesPrice) + orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2)
          orderConfirm.paymentPrice = (orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2)
          // 计算积分抵扣
          if (orderConfirm.pointsDeductSwitch === '1') {
            let pointsDeductPrice = Math.floor(orderConfirm.salesPrice * orderConfirm.pointsDeductScale / 100 * orderConfirm.quantity)
            let pointsDeduct = pointsDeductPrice / orderConfirm.pointsDeductAmount
            orderConfirm.paymentPointsPrice2 = pointsDeductPrice
            orderConfirm.paymentPrice2 = (orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2) - pointsDeductPrice
            if (pointsDeductPrice >= 1) {
              orderConfirm.paymentPoints2 = pointsDeduct
              totalPointsDeductPriceTemp = Number(totalPointsDeductPriceTemp) + Number(pointsDeductPrice)
              totalPointsDeduct = Number(totalPointsDeduct) + Number(pointsDeduct)
            }
          }
        })
        that.setData({
          orderConfirmData: orderConfirmData,
          salesPrice: salesPrice,
          paymentPrice: salesPrice,
          totalPointsDeduct: totalPointsDeduct,
          totalPointsDeductPriceTemp: totalPointsDeductPriceTemp,
          spuIds: spuIds
        })
        if (that.data.pointsCheckedValue) {
          that.pointsCheckedChange({
            detail: {
              value: that.data.pointsCheckedValue
            }
          })
        }
        if (that.data.couponCheckedValue) {
          that.couponUserChange({
            detail: {
              value: that.data.couponCheckedValue
            }
          })
        }
        that.couponUserPage()
      }
    })
  },
  //获取积分设置
  pointsConfigGet() {
    app.api.pointsConfigGet()
      .then(res => {
        this.setData({
          pointsConfig: res.data
        })
      })
  },
  //获取商城用户信息
  userInfoGet() {
    app.api.userInfoGet()
      .then(res => {
        this.setData({
          userInfo: res.data,
          [`orderSubParm.userName`]: res.data.nickName,
          [`orderSubParm.userPhone`]: res.data.phone
        })
      })
  },
  //提交订单
  orderSub() {
    let that = this
    let address = that.data.addressComponent.address
    let longitude = that.data.addressComponent.longitude
    let latitude = that.data.addressComponent.latitude
    let picUrls = that.data.picUrls || []
    // 判断数据
    let errorMsg = ""
    if (!address) {
      errorMsg = "请选择地址"
    } else if (!that.data.orderSubParm.userName) {
      errorMsg = "请输入姓名"
    } else if (!that.data.orderSubParm.userPhone) {
      errorMsg = "请输入电话"
    } else if (!that.data.orderSubParm.userMessage) {
      errorMsg = "请输入故障描述"
    } else if (picUrls.length===0) {
      errorMsg = "请上传故障图片"
    }
    if(errorMsg){
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      })
      return
    }
    that.setData({
      loading: true
    })
    let orderSubParm = that.data.orderSubParm
    let skus = that.data.orderConfirmData
    skus.forEach(function (sku) {
      sku.freightPrice = that.data.freightPrice
    })
    orderSubParm.skus = skus
    app.api.orderSub(Object.assign({}, {
          userAddress: address,
          longitude: longitude,
          latitude: latitude,
          picUrls: picUrls,
          bookingStartTime: that.data.bookingStartTime,
          bookingEndTime: that.data.bookingEndTime,
        },
        orderSubParm
      ))
      .then(res => {
        that.wxTemplateMsgList(res.data.id)
      }).catch(() => {
        that.setData({
          loading: false
        })
      })
  },
  //选择使用积分
  pointsCheckedChange(e) {
    if (e.detail.value == 'true') {
      let orderConfirmData = this.data.orderConfirmData
      let that = this
      orderConfirmData.forEach(function (orderConfirm) {
        if (orderConfirm.pointsDeductSwitch == '1') {
          orderConfirm.paymentPrice = orderConfirm.paymentPrice2 - that.data.totalCouponDeductPrice
          orderConfirm.paymentPoints = orderConfirm.paymentPoints2
          orderConfirm.paymentPointsPrice = orderConfirm.paymentPointsPrice2
        }
      })
      this.setData({
        pointsCheckedValue: e.detail.value,
        totalPointsDeductPrice: this.data.totalPointsDeductPriceTemp,
        paymentPrice: (Number(this.data.salesPrice) - Number(this.data.totalCouponDeductPrice) - Number(this.data.totalPointsDeductPriceTemp)).toFixed(2),
        orderConfirmData: orderConfirmData
      })
    } else {
      let orderConfirmData = this.data.orderConfirmData
      let that = this
      orderConfirmData.forEach(function (orderConfirm) {
        if (orderConfirm.pointsDeductSwitch == '1') {
          orderConfirm.paymentPrice = (orderConfirm.salesPrice * orderConfirm.quantity - that.data.totalCouponDeductPrice).toFixed(2)
          orderConfirm.paymentPoints = 0
          orderConfirm.paymentPointsPrice = 0
        }
      })
      this.setData({
        pointsCheckedValue: e.detail.value,
        totalPointsDeductPrice: 0,
        paymentPrice: (Number(this.data.salesPrice) - Number(this.data.totalCouponDeductPrice)).toFixed(2),
        orderConfirmData: orderConfirmData
      })
    }
  },
  //查询可用电子券
  couponUserPage() {
    app.api.couponUserPage({
        searchCount: false,
        current: 1,
        size: 50,
        descs: 'create_time',
        spuIds: this.data.spuIds
      })
      .then(res => {
        let couponUserList = res.data.records
        this.setData({
          couponUserList: couponUserList
        })
      })
  },
  showModalCoupon(e) {
    this.setData({
      modalCoupon: 'show'
    })
  },
  hideModalCoupon() {
    this.setData({
      modalCoupon: ''
    })
  },
  // 选择电子券
  couponUserChange(e) {
    let couponUser = this.data.couponUserList[e.detail.value]
    let orderConfirmData = this.data.orderConfirmData
    //先清空之前选择的券金额
    orderConfirmData.forEach((orderConfirm, index) => {
      orderConfirm.paymentCouponPrice = 0
    })
    //计算优惠金额
    if (couponUser.suitType == '1') { //1、全部服务适用，默认优惠第一个服务
      let orderConfirm = orderConfirmData[0]
      this.setPaymentCouponPrice(orderConfirm, couponUser)
      let temp = "orderConfirmData[0]"
      this.setData({
        [temp]: orderConfirm,
        totalCouponDeductPrice: orderConfirm.paymentCouponPrice
      })
    } else if (couponUser.suitType == '2') { //2、指定服务可用，默认优惠第一个指定服务
      try {
        orderConfirmData.forEach((orderConfirm, index) => {
          if (orderConfirm.spuId == couponUser.goodsSpu.id) {
            this.setPaymentCouponPrice(orderConfirm, couponUser)
            this.setData({
              totalCouponDeductPrice: orderConfirm.paymentCouponPrice
            })
            throw ("")
          }
        })
      } catch (e) {}
      this.setData({
        orderConfirmData: orderConfirmData
      })
    }
    this.setData({
      couponCheckedValue: e.detail.value,
      couponUser: couponUser,
      paymentPrice: (Number(this.data.salesPrice) - Number(this.data.totalCouponDeductPrice) - Number(this.data.totalPointsDeductPrice)).toFixed(2)
    })
  },
  setPaymentCouponPrice(orderConfirm, couponUser) {
    orderConfirm.couponUserId = couponUser.id
    let salesPrice = orderConfirm.salesPrice * orderConfirm.quantity
    if (couponUser.type == '1') { //代金券
      orderConfirm.paymentPrice = Number(salesPrice - couponUser.reduceAmount - this.data.totalPointsDeductPrice).toFixed(2)
      orderConfirm.paymentCouponPrice = couponUser.reduceAmount
    }
    if (couponUser.type == '2') { //折扣券
      let paymentCouponPrice = Number(salesPrice * (1 - couponUser.discount / 10)).toFixed(2)
      orderConfirm.paymentPrice = Number(salesPrice - paymentCouponPrice - this.data.totalPointsDeductPrice).toFixed(2)
      orderConfirm.paymentCouponPrice = paymentCouponPrice
    }
  },
  // 选择位置
  toMapPage() {
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=UVQBZ-PNY63-AZW32-35VCS-GC7VZ-EBFD3&referer=这里修车`
    });
  },
  ChooseImage() {
    const that = this
    wx.chooseMedia({
      count: 3, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      mediaType: ['image'],
      success: (res) => {
        let filePath = res.tempFiles[0].tempFilePath
        wx.showLoading({
          title: '加载中',
        })
        // 上传图片
        wx.uploadFile({
          url: __config.basePath + '/mall/api/ma/file/upload',
          filePath: filePath,
          header: {
            'app-id': wx.getAccountInfoSync().miniProgram.appId,
            'third-session': wx.getStorageSync('third_session') != null ? wx.getStorageSync('third_session') : ''
          },
          name: 'file',
          formData: {
            'fileType': 'image',
            'dir': 'order/detail/'
          },
          success (uploadFileRes){
            if(uploadFileRes.statusCode == '200'){
              let link = JSON.parse(uploadFileRes.data).link
              let picUrls = that.data.picUrls
              if(picUrls){
                picUrls.push(link)
              }else{
                picUrls = []
                picUrls.push(link)
              }
              that.setData({
                picUrls: picUrls
              })
            }else{
              wx.showModal({
                title: '提示',
                content: '上传失败：' + uploadFileRes.data,
                success(res) {}
              });
            }
          },
          fail: (err) => {
            console.log(err)
          },
          complete(res) {
            wx.hideLoading()
          }
        })
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.picUrls,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定删除？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.picUrls.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            picUrls: this.data.picUrls
          })
        }
      }
    })
  },
  // 选择服务项目
  selectGoods() {
    wx.switchTab({
      url: '/pages/goods/goods-category/index',
    })
  }
})